package com.jiwen.service;

import com.jiwen.dao.AppCategoryDao;
import com.jiwen.pojo.AppCategory;
import com.jiwen.vo.CategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author shrstart
 * @create 2023-12-16-10:57
 */

@Service
public class AppCategoryServiceImpl implements AppCategoryService {

    @Autowired
    AppCategoryDao appCategoryDao;

    @Override
    public CategoryVo selCategory() {

        /*所需要的数据*/
        List<CategoryVo> categoryVos = new ArrayList<>();

        /*数据库分类数据*/
        List<AppCategory> appCategorys = appCategoryDao.queryAllBy(null);

        /*装填数据*/
        for (AppCategory appCategory : appCategorys) {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(appCategory,categoryVo);

            categoryVos.add(categoryVo);
        }

        /*改变结构*/
        CategoryVo categoryVo = new CategoryVo();
        for (CategoryVo vo : categoryVos) {
            if(vo.getParentid() == null){
                categoryVo = findCategory(vo,categoryVos);
            }
        }

        return categoryVo;
    }

    private CategoryVo findCategory(CategoryVo vo, List<CategoryVo> categoryVos) {

        vo.setChildren(new ArrayList<>());

        for (CategoryVo categoryVo : categoryVos) {
            if(categoryVo.getParentid() == vo.getId()){
                vo.getChildren().add(categoryVo);
                findCategory(categoryVo,categoryVos);
            }
        }

        return vo;
    }
}
